<?php

class post extends userQueries{
    public function getListTableName($tblName){
        $fields = array();
        $result = $this->query("SHOW COLUMNS FROM " . $tblName,"array");
        $f = "";
        for($a=0;$a<count($result);$a++){
           array_push($fields, array($result[$a]['Field']=>$result[$a]['Field']));
        }
        
        return $fields;
   }

    public function createPost($getpost,$auth,$type,$postPrivacyType,$postPrivacyIDs){
        $date = $this->currentDateTime();
  
        $post = stripslashes(htmlspecialchars($getpost,ENT_QUOTES));
                $insert = array("post"          =>      $post,
                                "postedBy"      =>      $auth['id'],
                                "date_posted"   =>      $date,
                                "post_type"     =>      $type,
                                "date_updated"   =>      $date,
                                "postPrivacyType" =>    $postPrivacyType,
                                "postPrivacyIDs" =>     $postPrivacyIDs,
                                "is_active"     =>      1);
                
                $postID = $this->insert("tbpost",$insert);
                
                // Audit Logs
                $this->auditLogs($auth,"tbpost","4",$postID);
            
                return $postID;
    }
    
    public function returnPost($auth,$post,$encodePostImage,$postID,$other,$type,$postPrivacyType){
        $date = $this->currentDateTime();
        
        if($type=="return"){
            $return_post = str_replace(array("&lt;a&gt;", "&lt;br&gt;", "&lt;/a&gt;"), array("<a>","<br>", "</a>"), $post);
            $return = array("postID"    =>      $postID,
                        "post"          =>      $return_post,
                        "authID"        =>      $auth['id'],
                        "privacy"       =>      "",
                        "date"          =>      $date,
                        "noti"          =>      "Post was successfully posted.",
                        "createdBy"     =>      $auth['first_name']. " " .$auth['last_name'],
                        "images"        =>      $this->avatarPic("tbuser",$auth['id'],"44","44","small","avatar "),
                        "user_level_id" =>      $auth['user_level_id'],
                        "userID"        =>      $auth['id'],
                        "position"      =>      $auth['position'],
                        "date_updated"  =>      $date,
                        "postPrivacyType"  =>   $postPrivacyType,
                        "profile"       =>      $other['last_name']. "_" .$other['first_name'],
                        "link"          =>      $this->curPageURL('port') . "/post?view_type=view_post&postID=" . $this->base_encode_decode("encrypt",$postID),
			"view_all"	=>	"no",
                        "starred"       =>      $this->get_starred($other['postID']));
	}elseif($type=="query"){
            $return_post = str_replace(array("&lt;a&gt;", "&lt;br&gt;", "&lt;/a&gt;"), array("<a>","<br>", "</a>"), $other['post']);
            $return = array(
                        "postID"        =>      $other['postID'],
                        "post"          =>      htmlspecialchars_decode($return_post),
                        "authID"        =>      $auth['id'],
                        "privacy"       =>      "",
                        "date"          =>      $other['date_posted'],
                        "noti"          =>      "Post was successfully load.",
                        "createdBy"     =>      $other['first_name']. " " .$other['last_name'],
                        "images"        =>      $this->avatarPic("tbuser",$other['postedBy'],"44","44","small","avatar "),
                        "user_level_id" =>      $auth['user_level_id'],
                        "userID"        =>      $other['postedBy'],
                        "position"      =>      $other['position'],
                        "date_updated"  =>      $other['date_updated'],
                        "postPrivacyType"  =>   $other['postPrivacyType'],
                        "profile"       =>      $other['last_name']. "_" .$other['first_name'],
                        "authName"      =>      $auth['first_name']. " " .$auth['last_name'],
                        "getSeen"       =>      $this->get_seen($other['postID']),
                        "link"          =>      $this->curPageURL('port') . "/post?view_type=view_post&postID=" . $this->base_encode_decode("encrypt",$other['postID']),
			"view_all"	=>	"no",
                        "starred"       =>      $this->get_starred($other['postID']));
        }elseif($type=="loadSingle"){
            $return_post = str_replace(array("&lt;a&gt;", "&lt;br&gt;", "&lt;/a&gt;"), array("<a>","<br>", "</a>"), $other['post']);
            $return = array(
                        "postID"        =>      $other['postID'],
                        "post"          =>      htmlspecialchars_decode($return_post),
                        "authID"        =>      $auth['id'],
                        "privacy"       =>      "",
                        "date"          =>      $other['date_posted'],
                        "noti"          =>      "Post was successfully load.",
                        "createdBy"     =>      $other['first_name']. " " .$other['last_name'],
                        "images"        =>      $this->avatarPic("tbuser",$other['postedBy'],"44","44","small","avatar "),
                        "user_level_id" =>      $auth['user_level_id'],
                        "userID"        =>      $other['postedBy'],
                        "position"      =>      $other['position'],
                        "date_updated"  =>      $other['date_updated'],
                        "postPrivacyType"  =>   $other['postPrivacyType'],
                        "profile"       =>      $other['last_name']. "." .$other['first_name'],
                        "authName"      =>      $auth['first_name']. " " .$auth['last_name'],
                        "getSeen"       =>      $this->get_seen($other['postID']),
                        "link"          =>      $this->curPageURL('port') . "/post?view_type=view_post&postID=" . $this->base_encode_decode("encrypt",$other['postID']),
			"view_all"	=>	"yes",
                        "starred"       =>      $this->get_starred($other['postID']));
        }
        
        
        
        return $return;
    }

    public function createComment($comment,$type,$postID,$auth,$fID,$decode_img,$folder_name) {
        $getAllTag = $_POST['getAllTag'];
        $date = $this->currentDateTime();
        // $reply = strip_tags($comment, '<a>');
        $reply = $comment;
            $insert = array("post_id"       =>  $postID,
                        "comment"           =>  $reply,
                        "postedBy"          =>  $auth['id'],
                        "date_posted"       =>  $date,
                        "commentType"       =>  $type,
                        "fID"               =>  $fID,
                        "is_active"         =>  1);
            
            $replyID = $this->insert("tbcomment",$insert);
            
            $updatePost = array("date_updated"=>$date);
            $whereupdatePost = array("id"=>$postID);

            $this->update("tbpost",$updatePost,$whereupdatePost);
		    // Create folder for the postImage
		  
                    $path = "images/" . $folder_name;
                    $id_encrypt = md5(md5($replyID));
		    $dir = $path."/".$id_encrypt;
                    if(count($decode_img)!=0){  
                        $this->createFolder($dir);
                    }
                        // Move files to the directory
                        $copy_foldername = md5(md5($auth['id']));
			$from = "images/" . $folder_name . "/temporaray_files/".$copy_foldername;
                        $postFiles = $this->getAllfiles_fromDirectory($from);
                            $ext_file = array();
			    $ext_img = array();
                                foreach($decode_img as $img){
                                    copy($from . '/' . $img, $dir . '/' . $img);
				    $extension = explode(".", $img);
				    $last_ext = $extension[count($extension)-1];
				    $valid_formats = unserialize(IMG_EXTENSION);
				    $path_resize_image = $dir . "/" . $img;
					if(!in_array($last_ext,$valid_formats)){
					    array_push($ext_file,$last_ext);
					}else{
					    array_push($ext_img,$last_ext);
					}
                                }
                            $this->unlinkRecursive($from, "");
                    
                    // Return        
                    $postImage = $this->getAllfiles_fromDirectory($dir);
                    
                    $encodePostImage = array("img"  =>  $decode_img,
                                               "postFolderName"     =>  $id_encrypt,
                                               "lengthImg"          => count($ext_img),
					       "extension_file"		    =>  $ext_file,
						    "extension_img"		    =>  $ext_img,
                                                    "image_resize"	=>	getimagesize($path_resize_image)
                                               );
                    
            
            $return = array("commentID"             =>      $replyID,
                            "postedBy"              =>      $auth['id'],
                            "postID"                =>      $postID,
                            "comment"               =>      $reply,
                            "commentBy"             =>      $auth['first_name']. " " .$auth['last_name'],
                            "commentType"           =>      $type,
                            "fID"                   =>      $fID,
                            "datePosted"            =>      $date,
                            "is_active"             =>      "1",
                            "images"                =>      $this->avatarPic("tbuser",$auth['id'],"44","44","small","avatar"),
                            "countComment"          =>      "",
                            "authID"                =>      $auth['id'],
                            "profile"               =>      $auth['last_name']. "_" .$auth['first_name'],
                            "attachment"            =>      $encodePostImage);
            
            // Save notificaion INsert notification
		   notifications::inserNotification("mentioncomment","tbcomment",$auth,array("postID"=>$replyID,"comment"=>$reply),$getAllTag);
           
        return $return;
   
            // Audit Logs
            $this->auditLogs($auth,"tbcomment","5",$replyID);
          
    }

    
    public function deletion($delAction,$postID){
        $auth = Auth::getAuth('current_user');
        
        if($delAction=="deletePost"){
            // Delete File
            $path = "images/postUpload";
            $id_encrypt = md5(md5($postID));
            $dir = $path."/".$id_encrypt;
            $this->unlinkRecursive($dir, "yes");
            
            $this->delete("tbpost",array("id"=>$postID)); // Delete the post
            $this->delete("tbcomment",array("post_id"=>$postID)); // Delete Also the comment of the post
            $this->delete("tblike",array("post_id"=>$postID)); // Delete Also the like of the post
	    // Audit Logs
            $this->auditLogs($auth,"tbpost","9",$postID);
            echo "Post was successfully deleted.";
            
        }elseif($delAction=="deleteComment"){
            $this->delete("tbcomment",array("id"=>$postID)); // Delete the comment
            $this->delete("tblike",array("post_id"=>$postID)); // Delete Also the like of the comment
	    // Audit Logs
            $this->auditLogs($auth,"tbcomment","10",$postID);
            echo "Comment was successfully deleted.";
            
            $path = "images/commentAttachment";
            $id_encrypt = md5(md5($postID));
            $dir = $path."/".$id_encrypt;
            $this->unlinkRecursive($dir, "yes");
        }
    }
    
    public function likes_unlike($auth,$postID,$likeAction,$likeType,$LID){
        $date = $this->currentDateTime();
        $getLike = $this->query("SELECT * FROM tblike WHERE user_id={$this->escape($auth['id'])} AND post_id={$this->escape($postID)} AND likeType={$this->escape($likeType)}","numrows");
        
        
	
            
                if($likeAction=="likePost"){
                    if($getLike==0){
                            $insert = array("user_id"           =>      $auth['id'],
                                        "post_id"           =>      $postID,
                                        "date_liked"        =>      $date,
                                        "likeType"          =>      $likeType,
                                        "is_active"         =>      1);
                            $likeID = $this->insert("tblike",$insert);
                            
                                // Count the user like on the post
                                $getLikePerson = $this->query("SELECT * FROM tblike WHERE post_id={$this->escape($postID)}","numrows");
                            
			    
			    
			    
			    
                            $return = array("likeID"            =>      $likeID,
                                            "user"              =>      $auth['first_name']. " " .$auth['last_name'],
                                            "likeCount"         =>      $getLikePerson,
					   
                                            "userID"            =>      $auth['id']);
                            
                            // Audit Logs
                            $this->auditLogs($auth,"tblike","6",$likeID);
                            $updatePost = array("date_updated"=>$date);
                            $whereupdatePost = array("id"=>$postID);

                            $this->update("tbpost",$updatePost,$whereupdatePost);
			    
			    // Insert notification
			    notifications::inserNotification("like","tblike",$auth,array("postID"=>$postID,"searchID"=>$postID),$likeType);
			    
			    
			    
                        return json_encode($return);
                    }
                }elseif($likeAction=="unlikePost"){
                    $likeID = $LID;
                    $con = array("post_id"          =>      $postID,
                                 "likeType"         =>      $likeType,
                                 "user_id"          =>      $auth['id']);
                    $likeID = $this->delete("tblike",$con);
                    
                    // Audit Logs
                    $this->auditLogs($auth,"tblike","7",$likeID);
                    
                }
    }
    
    public function loadCommentPost($auth,$postID,$operator,$limit){
        //comment
        if($limit!=""){
            $limit =   " LIMIT " . $limit;
        }else{
            $limit = "";
        }
        $getComment = $this->query("SELECT *,c.id as commentID FROM tbcomment c
                                 LEFT JOIN tbuser u on c.postedBy=u.id
                                 WHERE $operator c.post_id={$this->escape($postID)} AND c.commentType={$this->escape(0)} ORDER BY c.id DESC $limit","array");
        
        $countComment = $this->query("SELECT *,c.id as commentID FROM tbcomment c
                                 LEFT JOIN tbuser u on c.postedBy=u.id
                                 WHERE $operator c.post_id={$this->escape($postID)} AND c.commentType={$this->escape(0)} ","numrows");
           
            foreach ($getComment as $dataC){
                
                $path = "images/commentAttachment";
                    $id_encrypt = md5(md5($dataC['commentID']));
                    $dir = $path."/".$id_encrypt;
                    $postFiles = $this->getAllfiles_fromDirectory($dir);
		    
			    $ext_file = array();
			    $ext_img = array();
                                foreach($postFiles as $img){
				    $extension = explode(".", $img);
				    $last_ext = $extension[count($extension)-1];
				    $valid_formats = unserialize(IMG_EXTENSION);
				    $path_resize_image = $dir . "/" . $img;
					if(!in_array($last_ext,$valid_formats)){
					    array_push($ext_file,$last_ext);
					}else{
					    array_push($ext_img,$last_ext);
					}
                                }
				
                    //
                        $encodePostImage = array(   "img"                   =>      $postFiles,
                                                    "postFolderName"        =>      $id_encrypt,
                                                    "lengthImg"             =>      count($ext_img),
                                                    "extension_file"	    =>      $ext_file,
						    "extension_img"	    =>      $ext_img,
                                                    "image_resize"	    =>	    getimagesize($path_resize_image)
                                               );
                
                $encodeComment[] = array("commentID"             =>      $dataC['commentID'],
                                        "postedBy"              =>      $dataC['postedBy'],
                                        "postID"                =>      $dataC['post_id'],
                                        "comment"               =>      htmlspecialchars_decode($dataC['comment']),
                                        "commentBy"             =>      $dataC['first_name']. " " .$dataC['last_name'],
                                        "commentType"           =>      $dataC['commentType'],
                                        "fID"                   =>      $dataC['fID'],
                                        "datePosted"            =>      $dataC['date_posted'],
                                        "is_active"             =>      $dataC['is_active'],
                                        "images"                =>      $this->avatarPic("tbuser",$dataC['postedBy'],"44","44","small","avatar"),
                                        "countComment"          =>      $countComment,
                                        "authID"                =>      $auth['id'],
                                        "user_level_id"         =>      $auth['user_level_id'],
                                        "position"              =>      $auth['position'],
                                        "profile"               =>      $dataC['last_name']. "_" .$dataC['first_name'],
                                        "getLikeComment"        =>      $this->loadLike($auth,$dataC['commentID'],"reply"),
                                        "attachment"            =>      $encodePostImage);
                
                
                
            }
            return $encodeComment;
    }
    
    public function loadLike($auth,$postID,$type){
        // Like POST
        $getLike = $this->query("SELECT *,l.id as likeID FROM tblike l
                              LEFT JOIN tbuser u on l.user_id=u.id
                              WHERE l.post_id={$this->escape($postID)} AND l.is_active={$this->escape(1)} AND likeType={$this->escape($type)} ORDER BY u.id ASC","array");
        
        $getLikeCount = $this->query("SELECT *,l.id as likeID FROM tblike l
                              LEFT JOIN tbuser u on l.user_id=u.id
                              WHERE l.post_id={$this->escape($postID)} AND l.is_active={$this->escape(1)} AND likeType={$this->escape($type)} ORDER BY u.id ASC","numrows");
        
        // Count the user like on the post
        $getLikePerson = $this->query("SELECT * FROM tblike WHERE
                                    user_id={$this->escape($auth['id'])} AND post_id={$this->escape($postID)} AND likeType={$this->escape($type)}","numrows");
       
       
        //$encodeLike = array();
        foreach($getLike as $dataL){
            // Likes View
                if($dataL['user_id']!=$auth['id']){
                    $user = $dataL['first_name']. " " .$dataL['last_name'];
                }else{
                    $user = "You";
                }
                
            $encodeLike[] = array("likeID"          =>      $dataL['likeID'],
                                  "user"            =>      $user,
                                  "postedID"        =>      $dataL['post_id'],
                                  "userID"          =>      $dataL['user_id'],
                                  "likeBtn"         =>      $getLikePerson,
                                  "likeType"        =>      $dataL['likeType'],
                                  "likeCount"       =>      $getLikeCount);
        }
        
        return $encodeLike;
    }
    
    public function get_comment($auth,$postID,$type,$limit,$formID){
        //comment
        if($limit!=""){
            $limit =   " LIMIT " . $limit;
        }else{
            $limit = "";
        }
        
        
        $comment = $this->query("SELECT *,c.id as commentID FROM tbcomment c
                                 LEFT JOIN tbuser u on c.postedBy=u.id
                                 WHERE c.post_id={$this->escape($postID)} AND c.fID={$this->escape($formID)} AND c.commentType={$this->escape($type)} ORDER BY c.id DESC $limit","array");
        
        $count_comment = $this->query("SELECT *,c.id as commentID FROM tbcomment c
                                 LEFT JOIN tbuser u on c.postedBy=u.id
                                 WHERE c.post_id={$this->escape($postID)} AND c.fID={$this->escape($formID)} AND c.commentType={$this->escape($type)} ORDER BY c.id DESC $limit","numrows");
        
        foreach ($comment as $dataC){
            
            $path = "images/commentAttachment";
                    $id_encrypt = md5(md5($dataC['commentID']));
                    $dir = $path."/".$id_encrypt;
                    $postFiles = $this->getAllfiles_fromDirectory($dir);
		    
			    $ext_file = array();
			    $ext_img = array();
                                foreach($postFiles as $img){
				    $extension = explode(".", $img);
				    $last_ext = $extension[count($extension)-1];
				    $valid_formats = unserialize(IMG_EXTENSION);
				    $path_resize_image = $dir . "/" . $img;
					if(!in_array($last_ext,$valid_formats)){
					    array_push($ext_file,$last_ext);
					}else{
					    array_push($ext_img,$last_ext);
					}
                                }
				
                    //
                        $encodePostImage = array("img"            =>  $postFiles,
                                               "postFolderName"     =>  $id_encrypt,
                                               "lengthImg"          => count($ext_img),
					       "extension_file"		    =>  $ext_file,
						    "extension_img"		    =>  $ext_img,
                                                    "image_resize"	=>	getimagesize($path_resize_image)
                                               );
                        
            $encodeComment[] = array("commentID"            =>      $dataC['commentID'],
                                    "postedBy"              =>      $dataC['postedBy'],
                                    "postID"                =>      $dataC['post_id'],
                                    "comment"               =>      htmlspecialchars_decode($dataC['comment']),
                                    "commentBy"             =>      $dataC['first_name']. " " .$dataC['last_name'],
                                    "commentType"           =>      $dataC['commentType'],
                                    "fID"                   =>      $dataC['fID'],
                                    "datePosted"            =>      $dataC['date_posted'],
                                    "is_active"             =>      $dataC['is_active'],
                                    "images"                =>      $this->avatarPic("tbuser",$dataC['postedBy'],"44","44","small","avatar"),
                                    "countComment"          =>      $count_comment,
                                    "authID"                =>      $auth['id'],
                                    "user_level_id"         =>      $auth['user_level_id'],
                                    "position"              =>      $auth['position'],
                                    "profile"               =>      $dataC['last_name']. "." .$dataC['first_name'],
                                    "getLikeComment"        =>      $this->loadLike($auth,$dataC['commentID'],"reply"),
                                    "attachment"            =>      $encodePostImage);
        }
        return $encodeComment;
    }
    
    
    public function get_seen($postID){
        $getSeen = $this->query("SELECT * FROM tbseen s
                                LEFT JOIN tbuser u on u.id=s.userID
				LEFT JOIN tborgchartobjects o on o.id=u.department_id
                                WHERE s.seen_id={$this->escape($postID)} AND s.type={$this->escape(2)}","array");
        $db = new Database();
        foreach($getSeen as $seen){
            $encodeSeen[] = array(  "postID"	=>	$postID,
				    "type"	=>	2,
				    "userID"	=>	$seen['userID'],
				    "dateSeen"	=>	$seen['date'],
                                    "image"     =>      $this->avatarPic("tbuser",$seen['userID'],"44","44","small","avatar"),
                                    "departmentName"  => $seen['department'],
                                    "urlProfile"=>      $seen['last_name']. "_" .$seen['first_name'],
                                    "nameSeen"  =>      $seen['first_name']. " " .$seen['last_name'],
                                );
        }
        return $encodeSeen;
    }
    
    public function get_starred($postID){
        $get_starred = $this->query("SELECT *, s.id as starredID FROM tbstarred s
                                LEFT JOIN tbuser u on u.id=s.user_id
                                WHERE type={$this->escape(1)} AND data_id={$this->escape($postID)}","array");
        $starred_count = $this->query("SELECT *, s.id as starredID FROM tbstarred s
                                LEFT JOIN tbuser u on u.id=s.user_id
                                WHERE type={$this->escape(1)} AND data_id={$this->escape($postID)}","numrows");
        
        foreach($get_starred as $starred){
            $encodeStarred[] = array("starredID"    =>      $starred['starredID'],
                                     "table"        =>      $starred['tablename'],
                                     "postID"       =>      $starred['data_id'],
                                     "starredBy"    =>      $starred['user_id'],
                                     "nameStarredBy"=>      $starred['first_name']. " " .$starred['last_name']);
        }
	
		    
        return $encodeStarred;
    }
}

?>